package com.leetcode.array;

/**
 * Definition for singly-linked list.
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 */
public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int a = 0;
        int b = 0;
        if (l1 != null) {
            a = l1.val;
        }
        if (l2 != null) {
            b = l2.val;
        }
        int c = a + b;
        int pow = c / 10;
        int value = c % 10;
        ListNode result = new ListNode(value);
        result.next = addTwoNumbers(l1 == null ? null : l1.next, l2 == null ? null : l2.next, pow);
        return result;
    }

    private ListNode addTwoNumbers(ListNode l1, ListNode l2, int pow) {
        if (l1 == null && l2 == null) {
            if(pow>0){
                return new ListNode(pow);
            }else{
                return null;
            }
        }
        int a = 0, b = 0;
        if (l1 != null) {
            a = l1.val;
        }
        if (l2 != null) {
            b = l2.val;
        }
        int c = a + b + pow;
        pow = c / 10;
        int value = c % 10;
        ListNode result = new ListNode(value);
        result.next = addTwoNumbers(l1 == null ? null : l1.next, l2 == null ? null : l2.next, pow);
        return result;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        Solution solution = new Solution();
        ListNode result = solution.addTwoNumbers(l1, l2);
        System.out.println(result);
    }

}
